<template>
  <div class="order-statistics">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日订单数</span>
              <el-tag size="small" :type="todayOrderCount.trend > 0 ? 'success' : 'danger'">
                {{ todayOrderCount.trend > 0 ? '+' : '' }}{{ todayOrderCount.trend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-value">{{ todayOrderCount.value }}</div>
          <div class="card-footer">
            昨日：{{ todayOrderCount.yesterday }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日营业额</span>
              <el-tag size="small" :type="todayAmount.trend > 0 ? 'success' : 'danger'">
                {{ todayAmount.trend > 0 ? '+' : '' }}{{ todayAmount.trend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-value">¥{{ todayAmount.value.toFixed(2) }}</div>
          <div class="card-footer">
            昨日：¥{{ todayAmount.yesterday.toFixed(2) }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待处理订单</span>
            </div>
          </template>
          <div class="card-value">{{ pendingOrderCount }}</div>
          <div class="card-footer">
            待确认：{{ pendingConfirmCount }} | 待服务：{{ pendingServiceCount }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均客单价</span>
              <el-tag size="small" :type="averageAmount.trend > 0 ? 'success' : 'danger'">
                {{ averageAmount.trend > 0 ? '+' : '' }}{{ averageAmount.trend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-value">¥{{ averageAmount.value.toFixed(2) }}</div>
          <div class="card-footer">
            上周：¥{{ averageAmount.lastWeek.toFixed(2) }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单趋势</span>
              <el-radio-group v-model="trendTimeRange" size="small">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="orderTrendChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div class="chart-container" ref="orderStatusChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>服务项目分布</span>
            </div>
          </template>
          <div class="chart-container" ref="serviceDistributionChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>支付方式分布</span>
            </div>
          </template>
          <div class="chart-container" ref="paymentMethodChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>订单数据明细</span>
          <el-button type="primary" @click="handleExport">导出数据</el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="服务项目">
          <el-select v-model="searchForm.serviceId" placeholder="请选择" clearable>
            <el-option
              v-for="item in serviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="serviceName" label="服务项目" min-width="150" />
        <el-table-column prop="orderCount" label="订单数" width="100" />
        <el-table-column prop="amount" label="营业额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="averageAmount" label="客单价" width="120">
          <template #default="{ row }">
            ¥{{ row.averageAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="100">
          <template #default="{ row }">
            {{ row.completionRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="refundRate" label="退款率" width="100">
          <template #default="{ row }">
            {{ row.refundRate }}%
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  getMerchantOrderStatistics,
  exportMerchantOrders,
  getMerchantServiceList
} from '@/api/merchant'

// 统计数据
const todayOrderCount = reactive({
  value: 0,
  yesterday: 0,
  trend: 0
})

const todayAmount = reactive({
  value: 0,
  yesterday: 0,
  trend: 0
})

const pendingOrderCount = ref(0)
const pendingConfirmCount = ref(0)
const pendingServiceCount = ref(0)

const averageAmount = reactive({
  value: 0,
  lastWeek: 0,
  trend: 0
})

// 图表相关
const trendTimeRange = ref('week')
const orderTrendChartRef = ref(null)
const orderStatusChartRef = ref(null)
const serviceDistributionChartRef = ref(null)
const paymentMethodChartRef = ref(null)
let orderTrendChart = null
let orderStatusChart = null
let serviceDistributionChart = null
let paymentMethodChart = null

// 表格相关
const loading = ref(false)
const searchForm = reactive({
  dateRange: [],
  serviceId: ''
})
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})
const tableData = ref([])
const serviceOptions = ref([])

// 初始化图表
const initCharts = () => {
  // 订单趋势图
  orderTrendChart = echarts.init(orderTrendChartRef.value)
  // 订单状态分布图
  orderStatusChart = echarts.init(orderStatusChartRef.value)
  // 服务项目分布图
  serviceDistributionChart = echarts.init(serviceDistributionChartRef.value)
  // 支付方式分布图
  paymentMethodChart = echarts.init(paymentMethodChartRef.value)

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  orderTrendChart?.resize()
  orderStatusChart?.resize()
  serviceDistributionChart?.resize()
  paymentMethodChart?.resize()
}

// 更新订单趋势图
const updateOrderTrendChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['订单数', '营业额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数',
        position: 'left'
      },
      {
        type: 'value',
        name: '营业额',
        position: 'right',
        axisLabel: {
          formatter: '¥{value}'
        }
      }
    ],
    series: [
      {
        name: '订单数',
        type: 'bar',
        data: data.orderCounts
      },
      {
        name: '营业额',
        type: 'line',
        yAxisIndex: 1,
        data: data.amounts
      }
    ]
  }
  orderTrendChart?.setOption(option)
}

// 更新订单状态分布图
const updateOrderStatusChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  orderStatusChart?.setOption(option)
}

// 更新服务项目分布图
const updateServiceDistributionChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '订单数',
        type: 'bar',
        data: data.map(item => item.count)
      }
    ]
  }
  serviceDistributionChart?.setOption(option)
}

// 更新支付方式分布图
const updatePaymentMethodChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  paymentMethodChart?.setOption(option)
}

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const params = {
      timeRange: trendTimeRange.value,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      serviceId: searchForm.serviceId
    }
    const { data } = await getMerchantOrderStatistics(params)
    
    // 更新统计卡片数据
    Object.assign(todayOrderCount, data.todayOrderCount)
    Object.assign(todayAmount, data.todayAmount)
    pendingOrderCount.value = data.pendingOrderCount
    pendingConfirmCount.value = data.pendingConfirmCount
    pendingServiceCount.value = data.pendingServiceCount
    Object.assign(averageAmount, data.averageAmount)

    // 更新图表数据
    updateOrderTrendChart(data.trendData)
    updateOrderStatusChart(data.statusDistribution)
    updateServiceDistributionChart(data.serviceDistribution)
    updatePaymentMethodChart(data.paymentMethodDistribution)

    // 更新表格数据
    tableData.value = data.tableData
    page.total = data.total
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取服务项目列表
const getServiceList = async () => {
  try {
    const { data } = await getMerchantServiceList()
    serviceOptions.value = data
  } catch (error) {
    console.error('获取服务项目列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getStatisticsData()
}

// 重置搜索
const handleReset = () => {
  searchForm.dateRange = []
  searchForm.serviceId = ''
  handleSearch()
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      serviceId: searchForm.serviceId
    }
    await exportMerchantOrders(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getStatisticsData()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getStatisticsData()
}

// 监听时间范围变化
watch(trendTimeRange, () => {
  getStatisticsData()
})

onMounted(() => {
  initCharts()
  getServiceList()
  getStatisticsData()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  orderTrendChart?.dispose()
  orderStatusChart?.dispose()
  serviceDistributionChart?.dispose()
  paymentMethodChart?.dispose()
})
</script>

<style lang="scss" scoped>
.order-statistics {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin: 10px 0;
    }

    .card-footer {
      font-size: 13px;
      color: #909399;
    }
  }

  .chart-row {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .search-form {
      margin-bottom: 20px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 